<?php
function formatBacktrace($stack)
{
	$trace = array();

	foreach ($stack as $k => $v)
	{
		if (!isset($v['file']) || !isset($v['line']))
			continue;

		array_walk($v['args'], function (&$item, $key)
		{
			$item = var_export($item, true);
		});

		$trace[] = '#'.$k.' '.$v['file'].'('.$v['line'].'): '.
			(isset($v['class']) ? $v['class'].'->' : '').$v['function'].'('.implode(', ', $v['args']).')';
	}

	return implode('<br />', $trace);
}

function exceptionHandler($e)
{
	$backtrace = $e->getTraceAsString();
	$errorMessage = $e->getMessage().' ('.$e->getFile().':'.$e->getLine().')';

	$content = '<h3>Ошибка:</h3>'.$errorMessage;
	$content .= '<h3>Стек вызовов:</h3><pre>'.$backtrace.'</pre>';

	echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'.
		'<div style="padding: 20px; ">'.$content.'</div>';

	C::log()->write($errorMessage."\nСтек вызовов:\n".str_replace('<br />', "\n", $backtrace));
	C::app()->end();
}

function errorHandler($code, $message, $file, $line)
{
	$stack = debug_backtrace();
	array_shift($stack);
	$backtrace = formatBacktrace($stack);
	$errorMessage = $message.' ('.$file.':'.$line.')';

	$content = '<h3>Ошибка:</h3>'.$errorMessage;
	$content .= '<h3>Стек вызовов:</h3><pre>'.$backtrace.'</pre>';

	echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'.
		'<div style="padding: 20px; ">'.$content.'</div>';

	C::log()->write($errorMessage."\nСтек вызовов:\n".str_replace('<br />', "\n", $backtrace));
	C::app()->end();
}

set_exception_handler('exceptionHandler');
set_error_handler('errorHandler');